<template>
  <div class="app-container">
     <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="文件名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
        </el-col>
         <!-- <el-col :span="6">
            <el-form-item label="">
              <el-date-picker
                v-model="dateRange"
                style="width: 100%"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="创建日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>  -->
      </el-row> 
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-upload
            class="upload-demo"
            :action="uploadFileUrl"
            
                  :accept="'.xlsx'"
                  :show-file-list="false"
                   :headers="headers"
            :on-change="fileChange"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :file-list="fileList">
              <el-button
                type="primary"
                plain
                icon="el-icon-upload2"
                size="mini"
                :disabled="showBtn"
              >导入</el-button>
           
          </el-upload>
        <!-- <el-button
          type="primary"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleExport"
        >导入</el-button> -->
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
           :disabled="multiple"
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
     <el-table
     v-if="refreshTable"
      v-loading="loading"
      :data="categoryList"
      row-key="id"
      :check-strictly="true"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      :select-on-indeterminate="true"
      @select="select"
      @select-all="selectAll"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
      type="selection"
      width="55">
    </el-table-column>
      <el-table-column prop="fileName" label="文件名称">
        <template slot-scope="scope"> 
          <!-- <i class="el-icon-folder"></i>
          <span :style="{ paddingLeft: (scope.level *20) + 'px'}">{{scope.row.title}}</span> -->
          <!-- 子节点 -->
          <span>
            <i class="el-icon-folder"></i>
            <span style="margin:0 0 0 10px" >{{delHtmlTag(scope.row.title)}}</span>
          </span>
          <!-- <span v-else>
             <i class="el-icon-folder-opened"></i>
            <span style="margin:0 0 0 10px">{{scope.row.title}}</span>
          </span> -->
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注信息" width="200"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
          >详情</el-button>
          
        </template>
      </el-table-column>
    </el-table>
  
     <el-dialog   
    title="文件详情"
    :visible.sync="dialogDetail"
    :close-on-click-modal= 'false'
     width="40%">
     <p style="width:100%;text-align:center;font-weight:bold;font-size:15px" >{{detailFile.title}}</p>
     <p >{{detailFile.answer}}</p>
      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogDetail = false">返 回</el-button>
      </span>
     </el-dialog>

     <el-dialog   
    title="文件编辑"
    :visible.sync="dialogEdit"
    :close-on-click-modal= 'false'
     width="40%">
     <el-input type="textarea" :autosize="{minRows: 1,maxRows: 4}" v-model="detailFile.title" class="myinput"></el-input>
     <el-input style="margin-top: 20px;" type="textarea" :autosize="{minRows: 2, maxRows: 12}" v-model="detailFile.answer"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="handleSave">保存</el-button>
          <el-button @click="dialogEdit = false" size="small">返 回</el-button>
      </span>
     </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import {selKnowledge,updKnowledge,delKnowledge,editKnowledge} from '@/api/businessModule/knowledge'
export default {
  name: "knowledgeBase",
  data() {
    return {
      uploadFileUrl:process.env.VUE_APP_BASE_API + "/system/upload/knowledge",
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList:[],
      refreshTable: true,

      isEditing: false,
      editedText: '',
      dialogEdit: false,
      dialogDetail:false,
      detailFile:{},
      dialogVisible:false,
      
      dateRange:[],
      categoryList: [],
      showSearch:true,
       // 是否展开，默认全部展开
      isExpandAll: true,
      // 是否显示格式
      isFlag:false,
      isShow: false,
      // 遮罩层
      loading: true,
      showBtn:false,
      // 选中数组
      ids: [],
      titles: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
     // showSearch: true,
      // 总条数
     // total: 0,
   
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      showdis:123,
      // 时间范围
      createTime:'',
      // 查询参数
      queryParams: {
        // pageNum: 1,
        // pageSize: 10,
        title:undefined,

      },
      fileForm:{
        fileId:"",
      },
     
    };
  },
  created() {
     this.getList();
  },

  methods: {
    // 上传成功回调
    handleUploadSuccess(res) {
      if(res.code==200){
         this.$message.success('导入成功')
         this.$nextTick(()=>{
           this.showBtn=false
            this.loading=false
            this.getList()
         })
      }else {
        
        this.$message.error('导入失败')
          this.$nextTick(()=>{
           this.showBtn=false
            this.loading=false
         })
      }

     
    },
     // 上传失败
    handleUploadError(err) {
        
      this.$message.error('导入失败')
          this.$nextTick(()=>{
           this.showBtn=false
            this.loading=false
         })
      
    },
    closeDialog(){
      this.dialogVisible=false
      this.fileList=[]
    },
    setChildren(children, type) {
      // 编辑多个子层级
      children.map(j => {
        this.toggleSelection(j, type)
        if (j.children) {
          this.setChildren(j.children, type)
        }
      })
    },
    // 选中父节点时，子节点一起选中取消
    select(selection, row) {
      const hasSelect = selection.some(el => {
        return row.id === el.id
      })
      if (hasSelect) {
        if (row.children) {
          // 解决子组件没有被勾选到
          this.setChildren(row.children, true)
        }
      } else {
        if (row.children) {
          this.setChildren(row.children, false)
        }
      }
    },
    toggleSelection(row, select) {
      if (row) {
        this.$nextTick(() => {
          this.$refs.multipleTable &&
            this.$refs.multipleTable.toggleRowSelection(row, select)
        })
      }
    },
    // 选择全部
    selectAll(selection) {
      // tabledata第一层只要有在selection里面就是全选
      const isSelect = selection.some(el => {
        const tableDataIds = this.categoryList.map(j => j.id)
        return tableDataIds.includes(el.id)
      })
      // tableDate第一层只要有不在selection里面就是全不选
      const isCancel = !this.categoryList.every(el => {
        const selectIds = selection.map(j => j.id)
        return selectIds.includes(el.id)
      })
      if (isSelect) {
        selection.map(el => {
          if (el.children) {
            // 解决子组件没有被勾选到
            this.setChildren(el.children, true)
          }
        })
      }
      if (isCancel) {
        this.tableData.map(el => {
          if (el.children) {
            // 解决子组件没有被勾选到
            this.setChildren(el.children, false)
          }
        })
      }
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    handleQuery(){
      this.getList();
    },
    resetQuery(){
      this.dateRange = [];
      this.resetFormData("queryForm");
      this.handleQuery();
    },
    getList(){
      this.loading = true;
      selKnowledge(this.addDateRange(this.queryParams,this.dateRange))
      .then(res=>{
        if(res.code == 200){
          console.log(res,"res>>>>>>>>>>");
           this.loading = false;
          this.categoryList = res.rows
        }
      })
    },
     handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.titles = selection.map(item => item.title);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    handleDelete(row){
      const userIds = row.id || this.ids;
      const titles = row.title || this.titles;
      this.$modal.confirm('删除后关联信息将无法恢复，请确认是否删除？').then(function() {
        return delKnowledge(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});


    },
    handleDetail(row){
      this.dialogDetail = true;
      this.detailFile ={
        ...row,
        title: this.delHtmlTag(row.title),
        answer:this.delHtmlTag(row.answer)
      }

    },
    delHtmlTag(str){
      return str.replace(/<[^>]+>/g,"");//去掉所有的html标记
    },
    handleEdit(row) {
       this.detailFile = {
        ...row,
        title: this.delHtmlTag(row.title),
        answer:this.delHtmlTag(row.answer)
      }
      this.dialogEdit = true
      this.isEditing = true
    },
    handleSave() {
     
      console.log(this.detailFile,"1111111");
      editKnowledge(this.detailFile).then(res => {
        console.log(res,"res");
         this.dialogEdit = false
         this.getList()

      })
    },
    handleExport(){
      // this.fileList = [];
      // this.dialogVisible = true;

    },
    //上传前的钩子函数
    beforeUpload(file){
      
    },
    fileChange(file,fileList){
      console.log(fileList);
      let name=file.name.slice(file.name.lastIndexOf(".") + 1)
      if(name=='xlsx'){
        // this.fileList = fileList
       this.loading=true
        this.showBtn=true
        
      }else {
        this.$message.warning('请上传.xlsx文件')
        
      }
     
    },
     handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件,请先删除再上传文件`);
     },
    confirmDialog(){
      if( this.fileList !=undefined &&this.fileList.length!==0){
        console.log(this.fileList);
        
        const formData = new FormData();
        formData.append("file", this.fileList[0].raw);
        updKnowledge(formData).then(res=>{
          if(res.code == 200){
            
             this.$message.success(res.msg);
             this.dialogVisible = false;
             this.fileList=[]
             this.getList()
           // this.fileForm.otherFile = res.result.url;
            //this.form.fileId = res.data.id;
          }else {
            
          }
        }).catch(err=>{
          
        })
        // this.dialogVisible = false;
        // this.fileList=[]
        // this.getList();
      }else{
         this.$message.warning('请先上传文件')
      }
    },
    cancleDialog(){
      this.dialogVisible = false;

    },
  }
};
</script>
<style scoped>
.myinput /deep/ .el-textarea__inner {
  text-align: center;
  font-weight: bold;
}
</style>